'use client'
import React, {useEffect, useState} from "react";
import {User} from "@/app/lib/user";
import { PageResult, postFetch} from "@/app/lib/HttpProtocol";
import {
  Button,
   message,
  PaginationProps,
  Space,
  Table,
  TableProps,
} from "antd";
import {Security} from "@/app/lib/security";
import SearchForm from "@/app/home/system/user/SearchForm";
import EditModal from "@/app/home/system/user/EditModal";
import DeleteModal from "@/app/components/common/DeleteModal";
import AddModal from "@/app/home/system/user/AddModal";
import ChangePasswordModal from "@/app/home/system/user/ChangePasswordModal";
import UserDetailModal from "@/app/home/system/user/DetailModal";
import WorkDrawer from "@/app/home/system/user/WorkDrawer";

const styleSize = "small"

const apis = {
  userPageApi:'/user/page',
  userAddApi:'/user/add',
  userEditApi:'/user/update',
  userDeleteApi:'/user/delete',
  userPasswordChangeApi:'/user/changePassword',
  userWorksApi:'/user/workWithRoles/list',
}
const initPage:PageResult = {total:0,list:[]}
const initParams:any = {pageNum:1,pageSize:20};

const UserType = {
  0:"个人",
  1:"应用"
}

async function loadUserPage(params:any){
  return await postFetch(apis.userPageApi,params);
}

function addKey(users:User[]){
  return users.map(u => {
    Object.assign(u,{key:u.id});
    return u;
  })
}

// @ts-ignore
function getColumns(onEdit,onDelete,onChangePassword,onDetail,onWork):TableProps<User>['columns']{
  return [
    {
      title:'用户名',
      dataIndex:'username',
      key:'username',
      width:130,
    },{
      title:'昵称',
      dataIndex:'nickname',
      key:'nickname',
      width:130,
    },{
      title:'头像',
      dataIndex:'avatar',
      key:'avatar',
      width:50,
      render:(d) => d?<img src={d} alt="avatar" style={{ maxWidth:30,maxHeight:24,objectFit:"cover"}} />:""
    },{
      title:'类型',
      dataIndex:'type',
      key:'type',
      width:50,
      // @ts-ignore
      render:(type) => UserType[type]
    },{
      title:'添加人',
      key:'addNickname',
      dataIndex:'addNickname',
      width:130,
    },{
      title:'添加时间',
      key:'addTime',
      dataIndex:'addTime',
      width:130,
    },{
      title:'修改人',
      key:'lmNickname',
      dataIndex:'lmNickname',
      width:130,
    },{
      title:'修改时间',
      dataIndex:'lmTime',
      key:'lmTime',
      width:130,
    },{
      title:'操作',
      key:'action',
      render:(_,record) =>(
        <Space size="middle">
          <Security perm={apis.userEditApi}><Button size={styleSize} type="primary" onClick={() => onEdit(record)}>编辑</Button></Security>
          <Security perm={apis.userDeleteApi}><Button size={styleSize} type="primary" onClick={() => onDelete(record)}>删除</Button></Security>
          <Security perm={apis.userPasswordChangeApi}><Button size={styleSize} type="primary" onClick={() => onChangePassword(record)}>修改密码</Button></Security>
          <Security perm={apis.userPageApi}><Button size={styleSize} type="primary" onClick={() => onDetail(record)}>详情</Button></Security>
          <Security perm={apis.userWorksApi}><Button size={styleSize} type="primary" onClick={() => onWork(record)}>分配工作</Button></Security>
        </Space>
      )
    }
  ];
}
export default function Home() {
  const [page,setPage] = useState(initPage);
  const [params,setParams] = useState(initParams)
  useEffect(() => {
    loadPage();
  },[])
  const loadPage = () => {
    loadUserPage(params).then(page => {
      // @ts-ignore
      setPage(page);
    })
  }
  const pageChange: PaginationProps['onChange'] = (pageNum,pageSize) => {
    params.pageNum = pageNum;
    params.pageSize = pageSize;
    setParams({...params})
    loadPage();
  };
  const onSearchFinish = (values: any) => {
    Object.assign(params,values)
    setParams({...params})
    loadPage();
  };
  
  const [select,setSelect] = useState(new User())
  const [modalStatus,setModalStatus] =
    useState({add:false,edit:false,delete:false,changePassword:false,detail:false,work:false})
  function showEditModal(user:User) {
    setSelect({...user});
    modalStatus.edit = true;
    setModalStatus({...modalStatus})
  }
  function showDeleteModal(user:User){
    setSelect({...user});
    modalStatus.delete = true;
    setModalStatus({...modalStatus})
  }
  function showChangePasswordModal(user:User){
    setSelect({...user});
    modalStatus.changePassword = true;
    setModalStatus({...modalStatus})
  }
  function showAddModal(){
    modalStatus.add = true;
    setModalStatus({...modalStatus})
  }
  function showDetailModal(user:User){
    setSelect({...user});
    modalStatus.detail = true;
    setModalStatus({...modalStatus})
  }
  function onWorkClick(user:User){
    setSelect({...user});
    modalStatus.work = true;
    setModalStatus({...modalStatus})
  }
  function handleAddOk(user:User){
    postFetch(apis.userAddApi,user).then(id　=> {
      message.success("操作成功")
      modalStatus.add = false;
      setModalStatus({...modalStatus})
      loadPage();
    })
  }
  function  handleAddCancel(){
    modalStatus.add = false;
    setModalStatus({...modalStatus})
  }
  function handleEditOk(user:User){
    Object.assign(select,user);
    postFetch(apis.userEditApi,select).then(id　=> {
      message.success("操作成功")
      modalStatus.edit = false;
      setModalStatus({...modalStatus})
      loadPage();
    })
  }
  function handleEditCancel(){
    modalStatus.edit = false;
    setModalStatus({...modalStatus})
  }
  
  function handleDeleteOk(user:User){
    modalStatus.delete = false;
    setModalStatus({...modalStatus})
    postFetch(apis.userDeleteApi, {id:user.id}).then(id　=> {
      message.success("操作成功")
      loadPage();
    })
  }
  function  handleDeleteCancel(){
    modalStatus.delete = false;
    setModalStatus({...modalStatus})
  }
  function handleChangePasswordOk(userSecret:any){
    modalStatus.changePassword = false;
    setModalStatus({...modalStatus})
    postFetch(apis.userPasswordChangeApi, userSecret).then(id => {
      message.success("操作成功")
    })
  }
  function handleChangePasswordCancel(){
    modalStatus.changePassword = false;
    setModalStatus({...modalStatus})
  }
  function onDetailClose(){
    modalStatus.detail = false;
    setModalStatus({...modalStatus})
  }
  function handleWorkClose(){
    modalStatus.work = false;
    setModalStatus({...modalStatus})
  }
  return (<>
      <SearchForm onSearchFinish={onSearchFinish}/>
      <div style={{ marginTop: 16 }}>
        <Security perm={apis.userAddApi}><Button type="primary" onClick={showAddModal} size={"small"}>
          添加
        </Button></Security>
      </div>
      <Table columns={getColumns(showEditModal,showDeleteModal,showChangePasswordModal,showDetailModal,onWorkClick)}
             dataSource={addKey(page.list)} size={styleSize}
             scroll={{ y: 340 }}
             pagination={{total: page.total, showSizeChanger: true, onChange: pageChange,pageSize:params.pageSize,current:params.pageNum}}
      />
    {!modalStatus.edit && select ?<></>: <EditModal open={true} onEditOk={handleEditOk} onEditCancel={handleEditCancel} user={select}/>}
    {!modalStatus.delete && select ?<></>: <DeleteModal open={true} onDeleteOk={handleDeleteOk} onDeleteCancel={handleDeleteCancel} obj={select} />}
    {!modalStatus.add ?<></>: <AddModal open={true} onAddOk={handleAddOk} onAddCancel={handleAddCancel} />}
    {!modalStatus.changePassword && select ?<></>: <ChangePasswordModal open={true} onOk={handleChangePasswordOk} onCancel={handleChangePasswordCancel} user={select}/>}
    {!modalStatus.detail && select ?<></>: <UserDetailModal open={true} onClose={onDetailClose} user={select}/>}
    {!modalStatus.work && select ?<></>: <WorkDrawer open={true} onClose={handleWorkClose} user={select} />}
    </>
  );
}